<?php

class ProductsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','ajax','ajaxsell','processorder','processbill','ajaxorder','addtoorder','statistics','dailystatistics'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Products;
		$firms = Firms::model()->findAll(array("select"=>array("id","name")));
		

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Products']))
		{
			$model->attributes=$_POST['Products'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
			'firms'=>$firms
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$firms = Firms::model()->findAll(array("select"=>array("id","name")));
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Products']))
		{
			$model->attributes=$_POST['Products'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
			'firms'=>$firms
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		/*
			$dataProvider=new CActiveDataProvider('Products',array(
			'criteria'=>array(
				'select'=>array(
					'id','name','price'
				),
				'with'=>array(
					'stores'=>array('select'=>array('pricesell','datesell')),
					'firm'=>array('select'=>array('name'))
				),
				
			)));
		*/	

		$billid=Yii::app()->session->get('billid',0);
		$datebuy=Yii::app()->session->get("currentdate",date('Y-m-d'));
		$billname="None";
		if(isset($billid) && $billid>0)
		{
			$curBill = Bills::model()->findByPk($billid);
			$billname = $curBill->name;
		}
		
		$orderid=Yii::app()->session->get('orderid',0);
		$ordername="None";
		if(isset($orderid) && $orderid>0)
		{
			$curOrder = Orders::model()->findByPk($orderid);
			$ordername = $curOrder->name;
		}
		
		$model=new Products('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Products']))
		$model->attributes=$_GET['Products'];	
		
		$billsmodel=new Bills('search');
		$billsmodel->unsetAttributes();  // clear any default values
		if(isset($_GET['Bills']))
		$billsmodel->attributes=$_GET['Bills'];	
		if(empty($billsmodel->paid)) $billsmodel->paid=0;
			
		$firms = Firms::model()->findAll();
		$dataForFirmsDropdown = CHtml::listData($firms,"id","name");
		$dataForFirmsDropdown[-1]="Всі";
		ksort($dataForFirmsDropdown);

		$suppliers = Suppliers::model()->findAll();
		$dataForSuppliersDropdown = CHtml::listData($suppliers,"id","name");
		$dataForSuppliersDropdown[-1]="Всі";
		ksort($dataForSuppliersDropdown);
		
		$ordersmodel=new Orders('search');
		$ordersmodel->unsetAttributes();  // clear any default values
		if(isset($_GET['Orders']))
		$ordersmodel->attributes=$_GET['Orders'];	

		$allincome = Otherincome::model()->findAll(array("select"=>"id,name","condition"=>"active=1"));
		$dataForIncomesDropdown = CHtml::listData($allincome,"id","name");
		$alloutcome = Otheroutcome::model()->findAll(array("select"=>"id,name","condition"=>"active=1"));
		$dataForOutcomesDropdown = CHtml::listData($alloutcome,"id","name");
		
		$this->render('index',array(
			'model'=>$model,	
			'dataForFirmsDropdown'=>$dataForFirmsDropdown,
			'billsmodel'=>$billsmodel,
			'dataForSuppliersDropdown'=>$dataForSuppliersDropdown,
			'billid'=>$billid,
			'billname'=>$billname,
			'orderid'=>$orderid,
			'ordername'=>$ordername,
			'datebuy'=>$datebuy,
			'ordersmodel'=>$ordersmodel,
			'dataForIncomesDropdown'=>$dataForIncomesDropdown,
			'dataForOutcomesDropdown'=>$dataForOutcomesDropdown
		)
		);
	}
	
	public function actionDailystatistics()
	{
		$curdat = Yii::app()->session->get("currentdate",date('Y-m-d'));
		
		$soldprodmodel = new Store('search');
		$soldprodmodel->unsetAttributes();
		$soldprodmodel->datesell = $curdat;
		
		$gotprodmodel = new Store('search');
		$gotprodmodel->unsetAttributes();
		$gotprodmodel->datebuy = $curdat;
		
		$otherincomes = new Otherincomes('search');
		$otherincomes->unsetAttributes();
		$otherincomes->paydate = $curdat;
		
		$otheroutcomes = new Otheroutcomes('search');
		$otheroutcomes->unsetAttributes();
		$otheroutcomes->paydate = $curdat;
		
		$billsoutcomes = new Billsoutcome('search');
		$billsoutcomes->unsetAttributes();
		$billsoutcomes->date = $curdat;
		
		$orderincomes = new Ordersincome('search');
		$orderincomes->unsetAttributes();
		$orderincomes->paiddate = $curdat;
		$orderincomes->returned = '0';
		
		$orderret = new Ordersincome('search');
		$orderret->unsetAttributes();
		$orderret->paiddate = $curdat;
		$orderret->returned = 1;
		
		$this->render('dailystat',array(
			"currentdate"=>$curdat,
			"soldprodmodel"=>$soldprodmodel,
			"gotprodmodel"=>$gotprodmodel,
			"otherincomes"=>$otherincomes,
			"otheroutcomes"=>$otheroutcomes,
			"billsoutcomes"=>$billsoutcomes,
			"orderincomes"=>$orderincomes,
			"orderret"=>$orderret
		));
	}
	
	public function actionStatistics()
	{
		$startdate=Yii::app()->session->get("startdate",date('Y-m-d'));
		$enddate=Yii::app()->session->get("enddate",date('Y-m-d'));
	
		$model=new Products('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Products']))
		$model->attributes=$_GET['Products'];	
		
		$firms = Firms::model()->findAll();
		$dataForFirmsDropdown = CHtml::listData($firms,"id","name");
		$dataForFirmsDropdown[-1]="Всі";
		ksort($dataForFirmsDropdown);
		
		$this->render('statistics',array(
			'model'=>$model,
			'dataForFirmsDropdown'=>$dataForFirmsDropdown,
			'startdate'=>$startdate,
			'enddate'=>$enddate
		)
		);
	}
	
	public function actionAjax($id)
	{	
		$billid = 0;
		$datebuy = date('Y-m-d');
		$arrayForSelect = array("0"=>"None");
		$theProduct = $this->loadModel($id);
		$lastPrice = 0;
		if($theProduct->billprice>0)
		{
			$lastPrice = $theProduct->billprice;
		}
		else
		{
			$lastPrice = Yii::app()->db->createCommand("SELECT pricebuy FROM store WHERE pricebuy IS NOT NULL AND pricebuy>0 AND productid=$id ORDER BY datebuy DESC LIMIT 1")->queryRow();
			if(!$lastPrice) $lastPrice=0; else $lastPrice = $lastPrice['pricebuy'];
		}
		$datebuy=Yii::app()->session->get("currentdate",$datebuy);		
		$billid=Yii::app()->session->get("billid",$billid);
		if($billid>0)
		{
			$theBill = Bills::model()->findByPk($billid);
			if($theBill) $arrayForSelect[$theBill->id] = $theBill->name;
		}		
		$this->renderPartial("add",array(
		'datebuy'=>$datebuy,
		'selectedBillId'=>$billid,
		'arrayForSelect'=>$arrayForSelect,
		'name'=>$theProduct->name,
		'id'=>$theProduct->id,
		'lastPrice'=>$lastPrice));
	}
	
	public function actionAddtoorder()
	{
		if(isset($_POST['Orderproducts']))
		{
			$attributes = $_POST['Orderproducts'];
			$op = Orderproducts::model()->findByPk(array("orderid"=>$attributes['orderid'],"productid"=>$attributes['productid']));
			if(is_null($op))
			{
				if($attributes['count']>0)
				{
					$op = new Orderproducts;
					$op->attributes = $attributes;
					$op->insert();
				}
			}
			else
			{
				if($attributes['count']>0)
				{
					$op->attributes = $attributes;
					echo $op->save();
				}
				else
				{
					$op->deleteByPk(array("orderid"=>$attributes['orderid'],"productid"=>$attributes['productid']));
				}
			}
		}
	}
	
	public function actionProcessorder($action,$id)
	{
		$order = Orders::model()->findByPk($id);
		$errors = '';
		switch(trim(strtolower($action)))
		{
			case "change":
				Yii::app()->session->add('orderid',$order->id);
				Yii::app()->session->add('orderfirmid',$order->firmid);
				echo $this->renderPartial('currentorder',array('orderid'=>$order->id,'ordername'=>$order->name,'errors'=>$errors));
				break;	
			case "close":
				$order->statusid=3;
				$order->save();
				Yii::app()->session->remove('orderid');
				echo $this->renderPartial('currentorder',array('orderid'=>'','ordername'=>'','errors'=>$errors));
				break;
			case "form":
				$order->statusid=2;
				$result = $order->form();
				if($result===true)
				{
					$order->save();
					Yii::app()->session->remove('orderid');
					echo $this->renderPartial('currentorder',array('orderid'=>'','ordername'=>'','errors'=>$errors));
				}
				else 
				{
					$errors = $result;
					echo $this->renderPartial('currentorder',array('orderid'=>$order->id,'ordername'=>$order->name,'errors'=>$errors));
				}
				break;	
		}
	}
	
	public function actionProcessbill($action,$id)
	{		
		$bill = Bills::model()->findByPk($id);
		switch(trim(strtolower($action)))
		{
			case "change":				
				Yii::app()->session->add('billid',$bill->id);
				echo $this->renderPartial('currentbill',array('billid'=>$bill->id,'billname'=>$bill->name));
				break;		
			case "close":
				$bill->paid=1;
				$bill->save();
				Yii::app()->session->remove('billid');
				echo $this->renderPartial('currentbill',array('billid'=>'','billname'=>''));
				break;
		}
	}
	
	public function actionAjaxorder($id)
	{	
		$orderid = 0;
		$count = 1;
		$theProduct = $this->loadModel($id);
		$orderid=Yii::app()->session->get("orderid",$orderid);
		if($orderid>0)
		{
			$theOrder = Orders::model()->findByPk($orderid);
			$orderProduct = Orderproducts::model()->findByPk(array("orderid"=>$orderid,"productid"=>$id));
			if(!is_null($orderProduct)) $count = $orderProduct->count;
		}		
		$this->renderPartial("order",array(
		'name'=>$theProduct->name,
		'productid'=>$theProduct->id,
		'order'=>$theOrder->name,
		'orderid'=>$theOrder->id,
		'count'=>$count
		));
	}
	
	public function actionAjaxsell($id)
	{	
		//$orderid = 0;
		$datesell = Yii::app()->session->get("currentdate",date('Y-m-d'));
		$arrayForSelect = array("0"=>"None");
		//$selectedorderid = 0;
		$theProduct = $this->loadModel($id);
		$lastPrice = 0;
		if($theProduct->price>0)
		{
			$lastPrice = $theProduct->price;
		}
		else
		{		
			$lastPrice = Yii::app()->db->createCommand("SELECT pricesell FROM store WHERE pricesell IS NOT NULL AND pricesell>0 AND productid=$id ORDER BY datesell DESC LIMIT 1")->queryRow();
			if(!$lastPrice) $lastPrice=0; else $lastPrice = $lastPrice['pricesell'];
		}
		
		$datesell=Yii::app()->session->get("datesell",$datesell);
	
		//$orderid=Yii::app()->session->get("orderid",$orderid);
		//if($orderid>0)
		//{
		//	$theOrder = Orders::model()->findByPk($orderid);
		//	if($theOrder) $arrayForSelect[$theOrder->id] = $theOrder->name;
		//}		
		$this->renderPartial("sell",array(
		'datesell'=>$datesell,
		//'selectedOrderId'=>$selectedorderid,
		//'arrayForSelect'=>$arrayForSelect,
		'name'=>$theProduct->name,
		'id'=>$theProduct->id,
		'lastPrice'=>$lastPrice));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Products('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Products']))
			$model->attributes=$_GET['Products'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Products::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='products-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
